<?php
interface IEngine {
	function render();
}
require_once('internal/Head.php');

// Engine base class
class Engine implements IEngine {
	public $title, $subtitle, $footer, $head;
	protected $modNames, $modules;

	function __construct() {
		global $mae;
		$this->title = $mae['site_title'];
		$this->subtitle = $mae['site_subtitle'];
		$this->footer = $mae['site_footer'];
        $this->modNames = $this->fetchModules();
        $this->modules = array();

		$this->head = new Head;
		$this->head->add('meta',array('http-equiv' => 'Content-type','content' => 'text/html; charset=utf-8'));
		$this->head->setTitle($this->title);

		$this->initModules();
	}

	protected function siteTop() {
		?>
		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/2001/REC-xhtml11-20010531/DTD/xhtml11-flat.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
		<?php $this->head->write(); ?>
		</head>
		<body>
		<?php
	}
	protected function siteBottom() {
		?>
		</body>
		</html>
		<?php
	}
	protected function content() { /* This method must be inherited by another class which adds something */ }

	// Render whole page
	public function render() {
		$this->siteTop();
		$this->content();
		$this->siteBottom();
	}

    /*
     function displayModules(string $section)

     Loads every module for a specific section and displays it.
    */
    protected function displayModules($section) {
		// Checking if a section is set, if not, displaying an error
        if (!$section) error('engine/section');

		// Assigning the modules for the section to an array
		$mods = $this->modNames[$section];

        // Executing modules
        if (count($mods)<1) echo "<span>$section</span>\n";
        else {
			for ($i=0; $i<count($mods); $i++) {
				echo '<div class="module">'."\n";
				$this->modules[$mods[$i]]->execute();
				echo '</div>'."\n";
			}
        }
    }

    /*
     function fetchModules()

     Fills the modules array
    */
    protected function fetchModules() {
        global $db;
        $mods = array();

        // Executing the query
		$db->modeNum();
        $q = $db->query("SELECT m.shortname, sm.position FROM mae_sitemodules sm INNER JOIN mae_modules m USING (id) WHERE sm.published=1;");

		foreach ($q as $k => $r) $mods[$r[1]][] = $r[0];

        return $mods;
    }

    /*
     function initModules()

     Initializes every loaded module
    */
    protected function initModules() {
        $mods = $this->modNames;
        reset($mods);

        while (list($k, $v) = each($mods)) {
            $pos = $mods[$k];
            for ($i=0; $i<count($pos); $i++) {
                $m = $pos[$i];
                require_once("modules/site/$m/module.php");
                $this->modules[$m] = new $m($this);
            }
        }
    }
}
?>
